package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q> {

    /**
     * 注入mapper层对象
     */
    @Autowired
    private Mapper<T> mapper;

    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public T findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional //就近原则
    public void saveOrUpdate(T t) {
        
        //新增
        if (t.getId() == null){

            //只有设置了值的字段才会被新增进去
            mapper.insertSelective(t);

        }else {
            //根据主键修改,只有设置了值的字段才会被新增进去
            mapper.updateByPrimaryKey(t);
        }
    }
    
    @Override
    @Transactional //就近原则
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageList<T> findPage(Q q) {

        //分页查询
        //1.分页工具包
        PageHelper.startPage(q.getPage(), q.getSize());

        //2.调用方法
        List<T> ts = mapper.selectAll();

        //3.封装一个pageInfo对象
        PageInfo<T> pageInfo = new PageInfo<>(ts);

        //4.封装自定义的分页对象
        PageList<T> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());

        return pageList;
    }

}
